import React, { Component } from 'react'
import {ListBox} from '../../../components'
import UpdateUserPage from './Update'
import AsignRolePage from './AsignRole'
import AssignReportUserFactory from './AssignReportUserFactory'
import TransferComponent from './TransferComponent'
import {  Button, Modal, Form, Tabs, message } from 'antd';
import { fetchData } from '../../../components/AjaxConsumer'
import $ from 'jquery'

const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;

// 用户管理
export default class ListUserPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            fetchDataBackData:[],
            submitData: [],
            selectLoginName:'',
        };
        //行操作列表
        this.rowOperation = [
            
        ];
        //header 操作列表
        this.headerOperation = [
            {
                handleName: 'addUser',
                showName: '新增',
                iconClass: 'plus'
            },{
                handleName: 'edit',
                showName: '修改',
                iconClass: 'edit'
            },{
                handleName: 'delete',
                showName: '删除',
                iconClass: 'delete'
            },{
                handleName: 'assignRole',
                showName: '角色分配',
                iconClass: 'key'
            },{
                handleName: 'assignDataAuth',
                showName: '数据权限分配',
                iconClass: 'key'
            },{
                handleName: 'initPwd',
                showName: '密码重置',
                iconClass: 'code-o'
            }
        ];

        //table列表展示列配置
        //showName、columnName 必有属性， columnWidth 可选，默认100, columnHidden: true 列隐藏
        this.tableColumn = {
            storageKey: 'ListUserColumnConfig',
            data: [
                {
                    showName: 'id',
                    columnName: 'userId',
                    columnHidden:true,
                    foreverHidden: true
                },
                {
                    showName: '登录账户名',
                    columnName: 'loginName',
                    columnWidth: 130
                },{
                    showName: '用户类型',
                    columnName: 'userTypeCode',
                    showOption:[
                        {
                            optionKey:'0',
                            optionShow:'管理员'
                        },{
                            optionKey:'1',
                            optionShow:'集团用户'
                        },{
                            optionKey:'2',
                            optionShow:'工厂用户'
                        }
                    ]
                },{
                    showName: '人员姓名',
                    columnName: 'userName'
                }
                // ,{
                //     showName: '供应商编码',
                //     columnName: 'supplyCode',
                // }
                // ,{
                //     showName: '产业编码',
                //     columnName: 'factoryGroupCode',
                // }
                ,{
                    showName: '邮件地址',
                    columnName: 'email'
                },{
                    showName: '座机号',
                    columnName: 'phone'
                },{
                    showName: '手机号',
                    columnName: 'mobile',
                    columnWidth: 130
                },{
                    showName: '是否可登录',
                    columnName: 'loginFlag',
                    showOption:[
                        {
                            optionKey:'1',
                            optionShow:'是'
                        },{
                            optionKey:'0',
                            optionShow:'否'
                        }
                    ]
                },/*{
                 showName: '最后登录IP',
                 columnName: 'loginIp'
                 },*//*{
                 showName: '最后登录时间',
                 columnName: 'loginDate'
                 },*//*{
                 showName: '是否初始化标志',
                 columnName: 'initFlag'
                 },{
                 showName: '最后密码修改时间',
                 columnName: 'lastPwdModifed'
                 },*/{
                    showName: '创建人',
                    columnName: 'createBy',
                    columnHidden:true
                },{
                    showName: '创建时间',
                    columnName: 'gmtCreate',
                    columnHidden:true,
                    columnWidth: 140
                },{
                    showName: '更新人',
                    columnName: 'lastModifiedBy',
                    columnHidden:true
                },{
                    showName: '更新时间',
                    columnName: 'gmtModified',
                    columnHidden:true,
                    columnWidth: 140
                }
            ]
        };

        //搜索属性配置，如果字段不配置，默认是input搜索
        // 搜索类型：
        //      1、输入框 type='input'， 默认
        //      2、时间 type='date'
        //      3、数字 type='number'
        //      4、下拉框 type='select'
        this.searchComponentData = [
            {
                name:'mobile',
                type: 'input'
            },{
                name:'supplyCode',
                type: 'input'
            },{
                name:'gmtCreate',
                type: 'date',
                maxName:'gmtCreateMax', 
                minName:'gmtCreateMin',
                showTime: 1
            },{
                name:'gmtModified',
                type: 'date',
                maxName:'gmtModifiedMax', 
                minName:'gmtModifiedMin',
                showTime: 1
            },{
                name : 'loginFlag',
                type : 'select',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    },{
                        optionKey:'1',
                        optionShow:'是'
                    },{
                        optionKey:'0',
                        optionShow:'否'
                    }
                ]
            },{
                name : 'userTypeCode',
                type : 'select',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    },{
                        optionKey:'1',
                        optionShow:'集团用户'
                    },{
                        optionKey:'2',
                        optionShow:'工厂用户'
                    }
                ]
            }
        ];
    }
    

    rowHandles = (strHandles, rowObj) => {
        if(strHandles === 'edit'){
            this.editHandle(rowObj);
        }else if(strHandles === 'delete'){
            this.deleteHandle(rowObj);
        }else if(strHandles === 'addUser'){
            this.addUserHandle();
        }else if(strHandles == 'assignRole'){
            this.assignRoleHandle(rowObj);
        }else if(strHandles == 'assignDataAuth'){
            this.assignUserDataAuthHandle(rowObj);
        }else if(strHandles == 'initPwd'){
            this.initPwdHandle(rowObj);
        }
    }
    // 增加用户
    addUserHandle = () => {
        this.refs.updateUser.getFormData[1]={
            type : 'input',
            showName : '登录用户名',
            name : 'loginName',
            initialValue : '',
            required:'required',
            disable: false
        };
        this.refs.updateUser.getFormData[2]={
            type : 'select',
            showName : '用户类型',
            name : 'userTypeCode',
            initialValue : '',
            optionList:[                //必填  下拉框的信息
                // {
                //     optionKey:'1',
                //     optionShow:'集团用户'
                // },
                {
                    optionKey:'2',
                    optionShow:'工厂用户'
                }
            ],
            required:'required',
            disable: false
        };
        this.refs.updateUser.addUserHandle();
    }
    editHandle = (rowObj) => {
        // 只能选择一条限制
        if(rowObj.length == 0){
            Modal.error({
                title: '错误提示',
                content: '请选择一条数据',
            });
        }else if(rowObj.length > 1){
            Modal.error({
                title: '错误提示',
                content: '只能选择一条数据',
            });
        }else{
            this.refs.updateUser.getFormData[1]={
                type : 'input',
                showName : '登录用户名',
                name : 'loginName',
                initialValue : '',
                required:'required',
                disable: true
            };
            this.refs.updateUser.editHandle(rowObj[0].data);

            this.refs.updateUser.getFormData[2]={
                type : 'select',
                showName : '用户类型',
                name : 'userTypeCode',
                initialValue : '',
                optionList:[              //必填  下拉框的信息
                    {
                        optionKey:'1',
                        optionShow:'集团用户'
                    },
                    {
                        optionKey:'2',
                        optionShow:'工厂用户'
                    }
                ],
                required:'required',
                disable: true
            };
            this.refs.updateUser.editHandle(rowObj[1].data);
        }
    }

    deleteHandle = (rowObj) => {
        if(rowObj.length == 0){
            Modal.error({
                title: '错误提示',
                content: '请选择一条数据',
            });
        }else if(rowObj.length > 1){
            Modal.error({
                title: '错误提示',
                content: '只能选择一条数据',
            });
        }else{
            this.refs.updateUser.deleteHandle(rowObj[0].data)
        }
    }

    assignRoleHandle = (rowObj) =>{
       if(rowObj.length == 0){
            Modal.error({
                title: '错误提示',
                content: '请选择一条数据',
            });
        }else if(rowObj.length > 1){
            Modal.error({
                title: '错误提示',
                content: '只能选择一条数据',
            });
        }else{
            //传递参数--用户id
            let userId = rowObj[0].data.userId;
            this.refs.assignRole.initModal(userId);
        }
    }

    assignUserDataAuthHandle =(rowObj)=>{
        if(rowObj.length == 0){
            Modal.error({
                title: '错误提示',
                content: '请选择一条数据',
            });
        }else if(rowObj.length > 1){
            Modal.error({
                title: '错误提示',
                content: '只能选择一条数据',
            });
        }else{
            let userTypeCode = rowObj[0].data.userTypeCode;
            //传递参数--用户登录名
            let loginName = rowObj[0].data.loginName;
            if(userTypeCode=='1'){   
                //this.refs.assignReportUserFactory.initModal(loginName);
                Modal.warning({
                    title: '集团用户不需要数据权限分配',
                    //content: '集团用户不需要数据权限分配',
                });
            }else if(userTypeCode=='2'){
                //在这里初始化值
                // this.setState({ 
                //     visible:true, 
                //     selectLoginName:loginName
                // })
                const options= {
                    url: '/base/auth/data/'+loginName+'/buz/types',
                    type: 'post',
                    condition:{}
                };
                fetchData(
                    this,
                    options,
                    (res)=>{
                        //success回调函数
                        let submitData = [];
                        res.data.map((e,index)=>{
                            // let tempObj = {};
                            // tempObj.tabCode = e.tabCode;
                            // tempObj.tabSelectList = e.tabSelectList;
                            // submitData.push(tempObj);

                            submitData[e.tabCode] = e.tabSelectList.map((ee,eindex)=>{
                                return (
                                    ee.key
                                )
                            })
                        })
                        this.setState({
                            fetchDataBackData: res.data,
                            submitData:submitData,
                            visible:true, 
                            selectLoginName:loginName
                        })
                    },
                    (res)=>{

                    }
                )
            }
        }
    }

    initPwdHandle = (rowObj) =>{
        
        if(rowObj.length == 1){
            confirm({
                        title: '提示',
                        content: '您确定要重置密码吗？',
                        onOk() {
                            let loginName = rowObj[0].data.loginName;
                            let userName = rowObj[0].data.userName;

                            const options= {
                                url: '/base/auth/init/pwd',
                                type: 'post',
                                condition:{
                                    loginName:loginName,
                                    userName:userName
                                }
                            };
                            fetchData(
                                this,
                                options,
                                (res)=>{
                                    //success回调函数
                                    message.success('初始化为密码123456成功!');
                                }
                            );
                                },
                        onCancel() {
                        console.log('Cancel');
                        },
                    });
            }else{
                Modal.error({
                    title: '错误提示',
                    content: '请选择一条数据',
                });
            }
    }

    getTransferSubmitData = (tabName,targetKeys) => {
        // console.log('----------------tabName', tabName)
        // console.log('----------------targetKeys', targetKeys)
        let submitData = this.state.submitData;
        // submitData
        submitData[tabName] = targetKeys;
        this.setState({
            submitData
        });
    }

    handleCancel = () => {
        this.setState({ visible: false });
    }

    handleOk = () => {
        let _that=this;
        let submitData = this.state.submitData;
        let submitDataEnd = [];
        for(let e in submitData){
            let t = {};
            t.tabCode = e;
            let selectArr = [];
            submitData[e].map((ee)=>{
                let tt = {};
                tt.key = ee;
                tt.value='';
                selectArr.push(tt);
            });
            t.tabSelectList = selectArr;
            submitDataEnd.push(t);
        }
        // console.log('----提交的数据-----', submitDataEnd);
        let loginName = this.state.selectLoginName;
        // console.log('----提交的数据-----',JSON.stringify(submitDataEnd));
         $.ajax({
             url:'/base/auth/data/buz/u/'+loginName,
             type:'post',
             dataType: 'json',
             contentType:'application/json;charset=utf-8',
             data:JSON.stringify(submitDataEnd),
             success:function(data){
                if(data.code=='1'){
                    _that.handleCancel();
                    message.success('操作成功');
                }
             },
             error:function(e){
                alert(e);
             }
         });
    }
    callback = (key) => {
        console.log(key);
    }


    //刷新列表
    refreshHandle = () => {
        this.refs.listUser.refreshHandle();
    }

    render() {
        //当左侧隐藏时，列表宽度加上左侧的宽度，
        //1、当前this.props.isHideLeft 是从页面组件containers/Main/main.js传过来
        //2、this.props.isHideLeft 最顶级赋值是在页面 containers/Main/main.js
        let isHideLeft = this.props.isHideLeft;

        let fetchDataBackData = this.state.fetchDataBackData;
        console.log('------',fetchDataBackData)
        let tempNode;
        
        
        tempNode = <Tabs defaultActiveKey="0" onChange={this.callback}>
                    {
                        fetchDataBackData.map((e,index)=>{
                            return (
                                <TabPane  tab={e.tabName} key={index}>
                                    <TransferComponent 
                                        tabCode={e.tabCode}  
                                        initTabAllList={e.tabAllList}
                                        initTabSelectList={e.tabSelectList}
                                        getTransferSubmitData={this.getTransferSubmitData}
                                        isComponentReset={this.state.visible}
                                    />
                                </TabPane >
                            )
                        })
                    }
                </Tabs>

        return(
            <div>
                <ListBox
                    ref = 'listUser'
                    isHideLeft={isHideLeft}
                    title="用户管理"
                    tableColumnData = {this.tableColumn}
                    searchComponentData={this.searchComponentData}
                    url = '/base/auth/user/list'
                    rowHandles = {this.rowHandles}
                    rowOperation = {this.rowOperation}
                    headerOperation = {this.headerOperation}
                    isRowSingle = "true"
                />

                <UpdateUserPage
                    ref="updateUser"
                    refreshHandle = {this.refreshHandle}
                />

                <AsignRolePage
                    ref="assignRole"
                    refreshHandle = {this.refreshHandle}
                />

                <AssignReportUserFactory
                    ref="assignReportUserFactory"
                    refreshHandle = {this.refreshHandle}
                />

                <Modal
                    style={{top: '20px'}}
                    visible={this.state.visible}
                    title="数据权限分配"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    width={'850px'}
                    footer={[
                        <Button key="back" size="large" onClick={this.handleCancel}>取消</Button>,
                        <Button key="submit" type="primary" onClick={this.handleOk}>
                        确定
                        </Button>,
                    ]}
                    maskClosable={false}>
                    <Form
                        style={{
                        paddingTop: '20px',
                        paddingBottom: '20px'
                    }}>
                        <div style={{marginTop:'-20px'}}>
                            {tempNode}
                        </div>
                    </Form>
                </Modal>
                
            </div>
        )
    }
}
